package com.zzx.controller;

import cn.hutool.core.codec.Base64;
import com.zzx.entity.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api(tags = "文件处理模块")
@RestController
@RequestMapping("/FileHandle")
public class FileController {

    @Value("${pic.path}")
    private String picPath;

    @ApiOperation(value = "加载图片")
    @ApiImplicitParam(dataType = "string", name = "picUrl", value = "图片地址", required = true)
    @RequestMapping(value = "/loadImg", method = RequestMethod.POST)
    public ApiResult loadImg(@RequestParam String picUrl) {
        File file = new File(picPath + picUrl);
        if (!file.exists()) {
            return ApiResult.failed("无图片!");
        }
        return ApiResult.ok((Object) Base64.encode(file));
    }

    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public ApiResult uploadImg(@RequestParam("file") MultipartFile multipartFile, @RequestParam String companyId) {
        try {
            if (multipartFile.isEmpty()) {
                return ApiResult.failed("文件为空,请重新选择!");
            }
            // 上传的图片全部保存在 picPath 目录下
            File file = new File(picPath + companyId + File.separator);
            if (!file.exists()) {
                // 创建完整的目录
                file.mkdirs();
            }
            // 获取文件原始名(包含后缀名)
            String orgName = multipartFile.getOriginalFilename();
            // 获取文件名（不包括后缀）
            String prefixName = orgName.substring(0, orgName.lastIndexOf("."));
            // 获取文件后缀名
            String suffixName = orgName.substring(orgName.lastIndexOf("."));
            // 这是处理后的新文件名
            String fileName;
            if (orgName.contains(".")) {
                // 示例：avatar.123.png，经过处理后得到：avatar.123_1661136943533.png
                fileName = prefixName + "_" + System.currentTimeMillis() + suffixName;
            } else {
                // 上传的图片没有后缀（这压根就不算是一个正常的图片吧？）
                return ApiResult.failed("上传图片格式错误,请重新选择！");
            }
            String savePath = file.getPath() + File.separator + fileName;
            File saveFile = new File(savePath);
            // 将上传的文件复制到指定目录
            FileCopyUtils.copy(multipartFile.getBytes(), saveFile);
            // 返回给前端的图片保存路径；前台可以根据返回的路径拼接完整地址，即可在浏览器上预览该图片
            String path = companyId + File.separator + fileName;
            if (path.contains("\\")) {
                path = path.replace("\\", "/");
            }
            return ApiResult.ok(path);
        } catch (IOException e) {
            return ApiResult.failed(e.getMessage());
        }
    }
}
